package com.study.xml.utils;

import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;


/**
* @Name: JAXPDOMParseUtils
* @Description: JAXP-DOM解析工具类
* @Author: 李超	lc_jack@foxmail.com
* @CreateDate: 2017-2-26 上午9:33:05 
* @Version: V1.0
 */
public class JAXPDOMParseUtils {
	
	private static DocumentBuilder documentBuilder = null ;
	private static Transformer transformer = null ;

	static {
		DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance() ;
		TransformerFactory transformerFactory = TransformerFactory.newInstance() ;
		try {
			documentBuilder = documentBuilderFactory.newDocumentBuilder() ;
			transformer = transformerFactory.newTransformer() ;
		} catch (ParserConfigurationException | TransformerConfigurationException e) {
			e.printStackTrace();
		}
	}
	
	public static Document getDocument(String uri) {
		Document document = null ;
		try {
			document = documentBuilder.parse(uri) ;
		} catch (SAXException | IOException e) {
			e.printStackTrace();
		}
		return document ;
	}
	
	public static void writeDOM2XML(Document document, String uri) {
		Source xmlSource = new DOMSource(document) ;
		Result outputTarget = new StreamResult(uri) ;
		try {
			transformer.transform(xmlSource, outputTarget) ;
		} catch (TransformerException e) {
			e.printStackTrace();
		}
	}
}
